package arrays;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description: 27.移除元素
 * User: Li_yizYa
 * Date: 2025—03—20
 * Time: 19:36
 */
public class Solution2 {
    /**
     * 快慢指针法
     * @param nums
     * @param val
     * @return
     */
    private static int removeElement2(int[] nums, int val) {
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
            if (nums[fastIndex] != val) {
                nums[slowIndex++] = nums[fastIndex];
            }
        }
        return slowIndex;
    }
    private static int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            if (nums[left] == val) {
                int tmp = nums[left];
                nums[left] = nums[right];
                nums[right] = tmp;
                right--;
            } else {
                left++;
            }
        }
        return left;
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("请输入数组长度: ");
        int n = scan.nextInt();
        System.out.print("请输入数组数字: ");
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = scan.nextInt();
        }
        System.out.print("请输入要删除的值: ");
        int val = scan.nextInt();
        int retIndex = removeElement(nums, val);
        System.out.println("删除" + val + "后的数组为: ");
        for (int i = 0; i < retIndex; i++) {
            System.out.print(nums[i] + " ");
        }
    }

}
